import Stack from '../data-structures/stack-object';

/**
 * 十进制转换为二进制
 */
export function decimalToBinary(decNumber: number) {
    const remStack: Stack<number> = new Stack();
    let rem: number;
    let binaryString: string = '';

    while (decNumber > 0) {
        rem = Math.floor(decNumber % 2); // 取余
        remStack.push(rem); // 将余数推进栈里
        decNumber = Math.floor(decNumber / 2); // 用商更新待处理数
    }

    while (!remStack.isEmpty()) {
        binaryString += remStack.pop().toString(); // 取栈顶的数
    }

    return binaryString;
}

/**
 * 十进制转换为任意进制
 */
export function baseConverter(decNumber: number, base: number) {
    const remStack: Stack<number> = new Stack<number>();
    const digits: string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let rem: number;
    let baseString: string = '';

    if (!(base >= 2 && base <= 36)) {
        return '';
    }

    while (decNumber > 0) {
        rem = Math.floor(decNumber % base); // 取余
        remStack.push(rem); // 将余数推进栈里
        decNumber = Math.floor(decNumber / base); // 用商更新待处理数
    }

    while (!remStack.isEmpty()) {
        baseString += digits[remStack.pop()]; // 取栈顶的数
    }

    return baseString;
}
